<template>
  <div class="map-total-area w-full h-full relative">
    <!-- <div style="height: 80px; width: 100vw"></div> -->
    <div class="map-head">
      <div class="map-head-name">浦东教育师资分析</div>
    </div>
    <div class="map-area-main">
      <div id="map-area"></div>
    </div>
    <div v-if="showAllTools" class="absolute left-top-tools flex items-center justify-center">
      <div class="search-area flex items-center">
        <el-input style="width: 86%" size="small" placeholder="搜索学校名称" v-model="searchKey" clearable />
        <div class="search-area-icon h-full cursor-pointer" @click="searchSchools">
          <img src="../../src/assets/images/search.png" />
        </div>
      </div>
    </div>

    <div v-if="showAllTools" class="absolute map-tools cursor-pointer">
      <img src="../../src/assets/images/magnify.png" @click="mapZoomChange('1')" />
      <img src="../../src/assets/images/shrink.png" @click="mapZoomChange('-1')" />
    </div>

    <div v-if="showAllTools" class="right-menu absolute" :class="rightMenuClass()">
      <div class="relative h-full" :class="{ 'menu-all-area': showAllType }">
        <div v-if="showAllType" class="menu-area">
          <div style="margin-bottom: 2px">
            <div class="menu-outline menu-outline-first cursor-pointer" @click="showSchoolType = !showSchoolType">
              <img src="../assets/images/semesterTerm.png" />
              <span style="flex: 1; color: #000; letter-spacing: 2px">学段</span>
              <img style="width: 14px; height: 9px" :style="showSchoolType
                ? 'transform: rotate(180deg)'
                : 'transform: rotate(0)'
                " src="../assets/images/dropDown.png" />
            </div>
            <div v-if="showSchoolType">
              <div v-for="(item, index) in schoolType" :key="item.code"
                class="child-button flex items-center justify-center cursor-pointer" :style="{
                  backgroundColor:
                    schoolTypeSelect.includes(item.type) ? color[index] : '',
                }" :class="schoolTypeSelect.includes(item.type)
                  ? 'active-school-type pr-5'
                  : ''
                  " @click="clickCheckBox(item.type, 'schoolTypeSelect')">
                <img v-if="schoolTypeSelect.includes(item.type)" src="../assets/images/tick.png"
                  class="duihaoIcon mr-1.5" />
                <div>
                  {{ item.name }}
                </div>
              </div>
            </div>
          </div>
          <div>
            <div class="menu-outline cursor-pointer" @click="showSubjectType = !showSubjectType">
              <img src="../assets/images/subject.png" />
              <span style="flex: 1; color: #000; letter-spacing: 2px">学科</span>
              <img style="width: 14px; height: 9px" :style="showSubjectType
                ? 'transform: rotate(180deg)'
                : 'transform: rotate(0)'
                " src="../assets/images/dropDown.png" />
            </div>
            <div v-if="showSubjectType">
              <div v-for="item in subjectType" :key="item.code"
                class="child-button cursor-pointer flex items-center justify-center overflow-ellipsis overflow-hidden whitespace-nowrap"
                :class="subjectTypeSelect.includes(item.type)
                  ? 'active-button pr-5'
                  : ''
                  " @click="clickCheckBox(item.type, 'subjectTypeSelect')">
                <img v-if="subjectTypeSelect.includes(item.type)" src="../assets/images/tick.png"
                  class="duihaoIcon mr-1.5" />
                <div>
                  {{ item.name }}
                </div>
              </div>
            </div>
          </div>
          <div class="triangle triangle-bottom"></div>
        </div>
        <div style="position: absolute; width: 198px;height: 55px;"
          :style="{ bottom: showAllType ? '-62px' : '-61px', right: showAllType ? '38px' : '39px' }">
          <div class="condition-tool relative cursor-pointer">
            <div class="condition-tool-left absolute flex" @click="showTools = !showTools">
              <img v-if="showTools" src="../assets/images/horizontal-open.png">
              <img v-else src="../assets/images/horizontal-close.png">
              <span>工具</span>
            </div>
            <img src="../assets/images/school.png" />
            <div class="condition-tool-right absolute flex" @click="showAllType = !showAllType">
              <span>条件</span>
              <img :style="{ transform: showAllType ? 'rotate(180deg)' : 'rotate(0deg)' }"
                src="../assets/images/vertical-close.png">
            </div>
          </div>
        </div>
      </div>
    </div>
    <template v-if="showAllTools">
      <div v-if="showTools" class="tip-area absolute flex items-center">
        <el-dropdown trigger="click" placement="top" @command="drawArea">
          <!-- <span class="button-style"> 区域 </span> -->
          <div class="ability-point">
            <img class="ability-point-img" src="../assets/images/region.png" />
            <div class="ability-point-name">选区</div>
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item class="text-center" command="1">方圆1公里</el-dropdown-item>
            <el-dropdown-item class="text-center" command="5">方圆5公里</el-dropdown-item>
            <el-dropdown-item class="text-center" command="10">方圆10公里</el-dropdown-item>
            <el-dropdown-item class="text-center" command="custom">自定义</el-dropdown-item>
            <el-dropdown-item class="text-center" command="clear">清除区域</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <el-dropdown trigger="click" placement="top" @command="drawPolygon">
          <!-- <span class="button-style"> 绘图 </span> -->
          <div class="ability-point">
            <img class="ability-point-img" src="../assets/images/localDrawing.png" />
            <div class="ability-point-name">画区</div>
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item class="text-center" command="circle">圆形</el-dropdown-item>
            <el-dropdown-item class="text-center" command="rectangle">方形</el-dropdown-item>
            <el-dropdown-item class="text-center" command="custom">自定义</el-dropdown-item>
            <el-dropdown-item class="text-center" command="delAll">删除图形</el-dropdown-item>
            <el-dropdown-item class="text-center" command="closeMouseTool">退出画区模式</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <!-- <el-button round @click.stop="rulerClick('reset')">测距</el-button> -->
        <div class="ability-point cursor-pointer" @click.stop="rulerClick">
          <img class="ability-point-img" src="../assets/images/ranging.png" />
          <div class="ability-point-name">测距</div>
        </div>

        <div class="ability-point cursor-pointer" @click.stop="drawPolygon('marker')">
          <img class="ability-point-img" src="../assets/images/punctuation.png" />
          <div class="ability-point-name">标点</div>
        </div>

        <div class="ability-point cursor-pointer" @click.stop="clickPolygon">
          <img class="ability-point-img" src="../assets/images/regressionBegin.png" />
          <div class="ability-point-name">中心点</div>
        </div>

        <div class="ability-point cursor-pointer" @click.stop="clearMap">
          <img class="ability-point-img" src="../assets/images/delate.png" />
          <div class="ability-point-name">重置</div>
        </div>

        <div class="triangle triangle-right"></div>
      </div>
    </template>


    <div class="absolute eye-area">
      <img v-if="showAllTools" class="cursor-pointer" src="../../src/assets/images/eye-open.png"
        @click="showAllTools = false" />
      <img v-else class="cursor-pointer" src="../../src/assets/images/eye-close.png" @click="showAllTools = true" />
    </div>

    <!-- 弹窗控件 start -->
    <el-dialog title="单位信息" :visible.sync="dialogTableVisible" :width="dialogWidth" :fullscreen="dialogFullscreen"
      :top="dialogFullscreen ? '0vh' : '8vh'">
      <div style="border: 2px solid #3399FF" :style="{
        height: `calc(${dialogFullscreen ? 100 : 84}vh)`,
      }">
        <!-- height: `calc(${dialogFullscreen ? 100 : 84}vh  - 10px)`, -->
        <!-- 标题区域 -->
        <div class="count-head">
          <span>{{ gridHeadTitle }}</span>
          <!-- <span class="cursor-pointer el-icon-download count-head-export">导出</span> -->
          <div class="cursor-pointer count-head-change">
            <span>数据源：</span>
            <el-cascader v-model="dataSource" :options="dataResourceList" :show-all-levels="false" size="mini"
              @change="changeDataResource"></el-cascader>
          </div>
          <download-excel class="export-excel-wrapper" :data="gridData.columnData" :fields="excelLabel"
            :header="gridHeadTitle" name="数据.xls">
            <span class="cursor-pointer count-head-export">导出</span>
          </download-excel>
          <span class="cursor-pointer el-icon-close" @click.stop="dialogClose"></span>
          <span class="cursor-pointer dialog-full-screen" :class="dialogFullscreen
            ? 'el-icon-copy-document'
            : 'el-icon-full-screen'
            " @click.stop="dialogFullscreen = !dialogFullscreen"></span>
        </div>
        <div class="pop-area">
          <!-- 信息统计区域 -->
          <!-- <div class="count-info" :style="{
            height: tipEllipsisBtn && tipEllipsis ? 'auto' : `34px`,
          }">
            <div ref="countTip" :class="[{ 'count-info-tip': !tipEllipsis }]" :title="gridHeadTip" style="flex: 1">
              <div class="inline-block">
                <div class="count-info-img flex items-center justify-center">
                  <img class="inline-block" src="../assets/images/schoolIcon.png" />
                </div>
              </div>
              <span>
                {{ gridHeadTip }}
              </span>
            </div>
            <div class="count-info-btn" v-if="tipEllipsisBtn" @click="tipEllipsisClick()">
              {{ !tipEllipsis ? "展开" : "收起" }}
            </div>
          </div> -->
          <!-- 数据表格展示区域 -->
          <!-- :height="`calc(100% - 5px - ${gridHeadTipHeight}px)`" -->
          <el-table class="cursor-pointer" :data="gridData.columnData" height="100%" border show-summary
            :summary-method="getSummaries">
            <template v-for="(item, index) in gridData.columnLabel">
              <el-table-column v-if="!item.childFileld && !item.notShow" align="center" :fixed="item.fixed" :key="index"
                :property="item.property" :label="item.label" :width="item.with"
                :show-overflow-tooltip=true></el-table-column>
              <el-table-column :key="index" v-else-if="!item.notShow" align="center" :label="item.label">
                <el-table-column align="center" v-for="(citem, cindex) in item.childFileld" :key="cindex"
                  :property="citem.property" :label="citem.label" :width="citem.with"
                  :show-overflow-tooltip=true></el-table-column>
              </el-table-column>
            </template>
          </el-table>
        </div>
      </div>
    </el-dialog>
    <!-- 弹窗控件 end -->
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import schools from "./js/schools.js";
import xySchoolData from "./js/xySchoolData.js";
import areas from "./js/areas.js";

export default {
  name: "mapTest",
  data() {
    return {
      map: null,
      infoWindow: null,
      showAllTools: true, // 展示所有工具 （眼睛的功能）
      activeNames: ["schoolType", "subjectType"],
      dataSource: 'v1', // 选中的数据
      dataResourceList: [{
        value: 'v1',
        label: '采集数据'
      }, {
        value: 'v2',
        label: '平台数据'
      }], // 可选择的数据列表
      excelLabel: {},
      addPolygonList: [], // 绘图绘制的图形存放数组
      searchKey: "", // 搜素关键字
      infoWindowState: 0, // marker的信息窗体状态  0是未开启 1是开启 注意：特指非聚合点的信息窗体  区域的信息窗体不算
      schoolType: [
        {
          code: "1-1",
          type: "kindergarten",
          name: "幼儿园",
        },
        {
          code: "1-2",
          type: "primarySchool",
          name: "小学",
        },
        {
          code: "1-3",
          type: "juniorHighSchool",
          name: "初中",
        },
        {
          code: "1-4",
          type: "highSchool",
          name: "高中",
        },
        {
          code: "1-5",
          type: "specialSchool",
          name: "特教",
        },
      ],
      subjectType: [
        {
          code: "2-1",
          type: "wy",
          name: "语文",
        },
        {
          code: "2-2",
          type: "sx",
          name: "数学",
        },
        {
          code: "2-3",
          type: "yy",
          name: "英语",
        },
        {
          code: "2-4",
          type: "wl",
          name: "物理",
        },
        {
          code: "2-5",
          type: "hx",
          name: "化学",
        },
        {
          code: "2-6",
          type: "smkx",
          name: "生命科学",
        },
        {
          code: "2-7",
          type: "kx",
          name: "科学",
        },
        {
          code: "2-8",
          type: "zr",
          name: "自然",
        },
        {
          code: "2-9",
          type: "ls",
          name: "历史",
        },
        {
          code: "2-10",
          type: "dl",
          name: "地理",
        },
        {
          code: "2-11",
          type: "df",
          name: "道法/思政",
        },
        {
          code: "2-12",
          type: "yy1",
          name: "音乐",
        },
        {
          code: "2-13",
          type: "ms",
          name: "美术",
        },
        {
          code: "2-14",
          type: "xxkj",
          name: "信息科技",
        },
        {
          code: "2-15",
          type: "ldjs",
          name: "劳动技术",
        },
        {
          code: "2-16",
          type: "tyjs",
          name: "体健",
        },
        {
          code: "2-17",
          type: "xl",
          name: "心理",
        },
        {
          code: "2-18",
          type: "ry",
          name: "日语",
        },
        {
          code: "2-19",
          type: "ey",
          name: "俄语",
        },
        {
          code: "2-20",
          type: "tj",
          name: "特教",
        },
      ],
      showAllType: true,
      showTools: true,
      showSchoolType: true,
      showSubjectType: true,
      timer: null, // 防抖定时器
      schoolTypeSelect: [], // 选中的学校类型
      // subjectTypeSelect: "", // 选中的学科类型
      subjectTypeSelect: [], // 选中的学科类型
      aMap: null,
      labelsLayer: null,
      checkedNames: [],
      schools,   // 校方数据
      xySchoolData, // 心源提供的数据
      cluster: null, // 点聚合
      ruler: null,
      mousetoolMarkers: [], // 标点功能，图标信息存放位置
      customPolygonItem: null, // 自定义绘图绘制的图形
      overlays: [], // 地图形状覆盖集合
      mouseTool: null, // 鼠标工具
      selectNode: null, // 选中的节点
      selectareaData: [], // 选中区域中的数据
      circleRadius: 0, // 点击区域 范围半径
      areaCircle: null, // 标点区域
      color: ["#fd8888", "#f89928", "#60bb5e", "#7d8ad2", "#129ef7", '#10c0b1'], // 学段标点颜色
      tipColor: {
        '幼儿园': "#fd8888",
        '小学': "#f89928",
        '初中': "#60bb5e",
        '高中': "#7d8ad2",
        '特教': "#129ef7",
      },
      gridData: {
        columnLabel: [],
        columnData: [],
      },
      gridHeadTitle: "",
      gridHeadTip: "",
      gridHeadTipHeight: "32",
      dialogTableVisible: false,
      dialogFullscreen: false,
      tipEllipsis: true,
      tipEllipsisBtn: false,
      dialogWidth: "90%",
      schoolTypeIcon: {
        '幼儿园': require("../assets/images/kindergarten.png"),
        '小学': require("../assets/images/primarySchool.png"),
        '初中': require("../assets/images/junior.png"),
        '高中': require("../assets/images/highSchool.png"),
        '特教': require("../assets/images/specialSchool.png"),
      },
      selectedSchoolTypeIcon: {
        '幼儿园': require("../assets/images/semesterTerm-kinder-checked.png"),
        '小学': require("../assets/images/semesterTerm-primary-checked.png"),
        '初中': require("../assets/images/semesterTerm-junior-checked.png"),
        '高中': require("../assets/images/semesterTerm-high-checked.png"),
        '特教': require("../assets/images/semesterTerm-special-checked.png"),
      },
      mouseToolState: null, // 鼠标工具状态，再说你鼠标工具时点击不发生效果
    };
  },
  watch: {
    'gridData.columnLabel': {
      handler() {
        this.excelLabel = {}
        this.gridData.columnLabel.forEach((item) => {
          if (item.childFileld) {
            item.childFileld.forEach(fitem => {
              this.excelLabel[item.label + fitem.label] = fitem.property
            })
          } else if (!item.notShow) {
            this.excelLabel[item.label] = item.property
          }
        })
      }
    },
    schoolTypeSelect() {
      this.clearAreaCircle();
      if (this.schoolTypeSelect.length === 0) {
        return;
      }
      this.schoolDebounce()
      // this.showClusterNodes()
    },
    subjectTypeSelect() {
      this.schoolDebounce()
      // this.showClusterNodes()
    },
    gridHeadTip: {
      //弹窗文字是否超出显示区域
      immediate: true,
      handler() {
        this.tipEllipsisBtn = false;
        if (this.gridHeadTip && this.dialogTableVisible) {
          this.$nextTick(() => {
            const detailDom = this.$refs.countTip;
            this.tipEllipsisBtn =
              detailDom.clientHeight < detailDom.scrollHeight;
            this.tipEllipsis = false;
          });
        }
      },
    },
    dialogFullscreen: {
      //弹窗全屏缩放时提示文字显示处理
      immediate: true,
      handler() {
        if (this.gridHeadTip && this.dialogTableVisible) {
          this.tipEllipsisBtn = false;
          this.tipEllipsis = true;
          this.$nextTick(() => {
            const detailDom = this.$refs.countTip;
            this.tipEllipsisBtn =
              detailDom.clientHeight < detailDom.scrollHeight;
            this.tipEllipsis = false;
          });
        }
      },
    },
  },
  mounted() {
    this.timer = null
    this.initAMap();
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
    /*
    *  description: 在vue中使用的防抖函数
    *  param fnName {String}  函数名
    *  param time {Number}    延迟时间
    *  return: 处理后的执行函数
    */
    schoolDebounce() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      // 设置新的定时器
      this.timer = setTimeout(() => {
        // 在定时器结束时执行函数逻辑
        this.showClusterNodes()
      }, 500); // 设置防抖的时间间隔，例如500毫秒
    },
    changeDataResource() {
      const allSchools = this.getAllSelectedNodes(this.dataSource[0])
      const showSchools = this.gridData.columnData.map((item) => {
        return item.serialId
      })
      const temp = []
      for (const item of allSchools) {
        if (showSchools.includes(item.serialId)) {
          temp.push(item)
        }
      }
      this.infoPop(temp)
    },
    showClusterNodes() {
      this.delPolygon();
      if (this.schoolTypeSelect.length === 1) {
        switch (this.schoolTypeSelect[0]) {
          case "kindergarten":
            this.showPolygon(this.schools[this.schoolTypeSelect[0]], this.color[0]);
            break;
          case "primarySchool":
            this.showPolygon(this.schools[this.schoolTypeSelect[0]], this.color[1]);
            break;
          case "juniorHighSchool":
            this.showPolygon(this.schools[this.schoolTypeSelect[0]], this.color[2]);
            break;
          case "highSchool":
            this.showPolygon(this.schools[this.schoolTypeSelect[0]], this.color[3]);
            break;
          case "specialSchool":
            this.showPolygon(this.schools[this.schoolTypeSelect[0]], this.color[4]);
            break;
          default:
            break;
        }
      } else if (this.schoolTypeSelect.length > 0) {
        const allSchools = this.getAllSelectedNodes()
        this.showPolygon(allSchools, this.color[5]);
      }
    },
    // 获取被选中的学段 的所有节点 存放在一个数组中
    getAllSelectedNodes(type) {
      let allSchools = []
      if (type === 'v2') {
        this.schoolTypeSelect.forEach(item => {
          allSchools = allSchools.concat(this.xySchoolData[item])
        })
      } else {
        this.schoolTypeSelect.forEach(item => {
          allSchools = allSchools.concat(this.schools[item])
        })
      }
      return allSchools
    },
    clickCheckBox(type, list) {
      // 学科复选 学段单选处理
      if (Array.isArray(this[list])) {
        if (this[list].includes(type)) {
          const _index = this[list].findIndex((fit) => fit === type);
          this[list].splice(_index, 1);
        } else {
          this[list].push(type);
        }
      } else {
        if (this[list] === type) {
          this[list] = "";
        } else {
          this[list] = type;
        }
      }
    },
    showPolygon(showNodes, color) {
      this.initCluster(showNodes, color);
    },
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "277615777410918518a4e799a115a4e3",
      };
      AMapLoader.load({
        key: "7059ef42c2d348a71196329c94fe5407", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.Scale",
          "AMap.MarkerCluster",
          "AMap.RangingTool",
          "AMap.MouseTool",
          "AMap.CircleEditor",
          "AMap.RectangleEditor",
        ], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
        .then((AMap) => {
          this.aMap = AMap;
          this.map = new AMap.Map("map-area", {
            // 设置地图容器id
            viewMode: "2D", // 是否为3D地图模式
            zoom: 10, // 初始化地图级别
            zooms: [10.33, 20],
            // dragEnable: false,
            // zoomEnable: false,
            doubleClickZoom: false,
            mapStyle: "amap://styles/whitesmoke",
          });
          this.map.on("zoomend", () => {
            this.infoWindow.close(); // 地图缩放时 关闭信息窗体
            this.infoWindowState = 0;
          });

          // 地图其余的操作在这下面写

          this.mapOption(AMap);
          this.map.setFitView();
        })
        .catch((e) => {
          console.log(e);
        });
    },
    deleteCustomPolygon() {
      if (this.customPolygonItem) {
        this.map.remove(this.customPolygonItem.item)
        if (this.customPolygonItem.editor) {
          this.customPolygonItem.editor.close()
        }
      }
      this.customPolygonItem = null
    },
    mapOption(AMap) {
      // 电子围栏
      for (const item of areas.areas) {
        this.addPolygon(item, AMap);
      }

      // 初始化显示窗体
      this.infoWindow = new AMap.InfoWindow({
        anchor: "top-center",
        closeWhenClickMap: true,
        isCustom: true,
        offset: new AMap.Pixel(0, 8),
      });

      this.infoWindow.on('click', () => {
        this.dataSource = ['v1']  // 默认使用v1的数据
        this.markerTip()
      })

      this.labelsLayer = new AMap.LabelsLayer({
        zooms: [10.33, 20],
        zIndex: 1000,
        collision: true, //该层内标注是否避让
        allowCollision: true, //不同标注层之间是否避让
      });

      // 初始化鼠标工具
      this.mouseTool = new this.aMap.MouseTool(this.map);
      // 鼠标工具监听事件
      this.mouseTool.on("draw", (event) => {
        // console.log(event);
        // event.obj 为绘制出来的覆盖物对象
        if (["AMap.Marker", "Overlay.Polyline"].includes(event.obj.className)) {
          if (event.obj.className === "AMap.Marker") {
            this.mousetoolMarkers.push(event.obj);
            event.obj.on("click", (e) => {
              if (!this.mouseToolState) {
                this.$confirm("确定要删除该标记点吗?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                  .then(() => {
                    this.map.remove(e.target);
                  })
                  .catch(() => { });
              }
            });
          }
          return;
        }
        this.map.remove(event.obj);
        const pathList = [];
        event.obj.getPath().forEach((item) => {
          pathList.push([item.lng, item.lat]);
        });
        this.deleteCustomPolygon()
        const customPolygon = new this.aMap.Polygon({
          path: pathList,
          strokeColor: "#FF33FF",
          strokeWeight: 6,
          strokeOpacity: 0.2,
          fillOpacity: 0.4,
          fillColor: "#1791fc",
          // zIndex: 50,
          strokeStyle: "solid",
        });
        this.customPolygonItem = { item: customPolygon };
        if (this.schoolTypeSelect.length > 0) {
          customPolygon.on("click", (e) => {
            const datas = this.getAreaDatas(pathList);
            const periodCount = this.getAllPeriodCount(datas)
            this.infoWindow.setContent(
              `<div style="display:flex; align-items: center;flex-direction: column;">
                <div class="relative" style="box-shadow:0px 0px 6px 0px #3fb5f8;background-color: #fff; padding: 10px 20px;text-align: left;border-radius: 8px;max-width: 400px;border: 1px solid #11a4f8">
                  <span style="color: #11a4f8">画区内有，学校: ${datas.length}所</span>
                  <span class="mr-2">，其中：幼儿园：${periodCount[0]}，小学：${periodCount[1]}，初中：${periodCount[2]}，高中：${periodCount[3]}，特教：${periodCount[4]}</span>
                  <span class="cursor-pointer" style="color: #11a4f8;white-space: nowrap;">查看详情></span>
                  <div class="absolute" style="background-color: #fff;width: 12px;height: 12px;transform: rotate(135deg);border-color: transparent transparent #3399ff #3399ff;border-width:1px;border-style: solid;top: -6px;left:calc(50% - 6px);"></div>
                </div>
              </div>`
            );
            this.infoWindow.open(this.map, e.lnglat);
            this.infoWindowState = 1
            this.selectNode = {
              type: 'custom',
              value: datas
            }
          });
        }

        this.addPolygonList.push(customPolygon);
        this.map.add(customPolygon);
      });

      // 获取数据
      this.getPositionDatas();
    },
    drawPolygon(command) {
      if (
        this.schoolTypeSelect.length === 0 &&
        !["marker", "closeMouseTool"].includes(command)
      ) {
        this.$message.error("请先选择学段！");
        return;
      }
      this.mouseTool.close(false); // 关闭鼠标工具
      switch (command) {
        case "circle": {
          this.$message({
            message:
              "开启鼠标画圆模式。",
            type: "success",
          });
          this.mouseToolState = "circle";
          break;
        }
        case "rectangle": {
          this.$message({
            message:
              "开启鼠标画矩形模式。",
            type: "success",
          });
          this.mouseToolState = "rectangle";
          break;
        }
        case "custom": {
          this.mouseToolState = "custom";
          this.$message({
            message:
              "开启绘制多边形模式。",
            type: "success",
          });
          this.mouseTool.polygon({
            fillColor: "#00b0ff",
            strokeColor: "#80d8ff",
            strokeWeight: 6,
            strokeOpacity: 0.2,
            fillOpacity: 0.4,
            strokeStyle: "solid",
            // 线样式还支持 'dashed'
            // strokeDasharray: [30,10],
          });
          break;
        }
        case "marker": {
          this.mouseToolState = "marker";
          this.$message({
            message:
              "开启绘制点标注模式。",
            type: "success",
          });
          if (this.mousetoolMarkers.length > 0) {
            this.$confirm(
              "此操作将清除地图上绘制的所有标点，您确定要继续操作吗?",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
              .then(() => {
                this.mousetoolMarkers.forEach((item) => {
                  this.map.remove(item);
                });
                this.mousetoolMarkers = [];
              })
              .catch(() => { });
          }
          this.mouseTool.marker({
            content:
              '<img src="https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png" style="height: 25px; width: 20px;"></img>',
            offset: new this.aMap.Pixel(-10, -25),
          });
          break;
        }
        case "delAll": {
          this.$message({
            message: "删除成功！",
            type: "success",
          });
          this.deleteCustomPolygon()
          break;
        }
        case "closeMouseTool": {
          this.mouseTool.close(false); // 关闭鼠标工具
          this.mouseToolState = null;
          break;
        }
        default:
          break;
      }
    },
    clearAreaCircle() {
      if (this.areaCircle) {
        this.map.remove(this.areaCircle);
      }
    },
    drawArea(command) {
      this.clearAreaCircle();
      switch (command) {
        case "1":
          this.circleRadius = 1000;
          this.addCircle(this.circleRadius);
          break;
        case "5":
          this.circleRadius = 5000;
          this.addCircle(this.circleRadius);
          break;
        case "10":
          this.circleRadius = 10000;
          this.addCircle(this.circleRadius);
          break;
        case "custom":
          this.$prompt(
            "请输入要查询的范围（最多支持两位小数, 单位：公里）",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              inputPattern: /^([1-9][0-9]*)+(.[0-9]{1,2})?$/,
              inputErrorMessage: "查询范围输入格式不正确",
            }
          )
            .then(({ value }) => {
              this.circleRadius = Number(value) * 1000;
              this.addCircle(this.circleRadius);
            })
            .catch(() => { });
          break;
        default:
          break;
      }
    },
    addCircle() {
      if (this.selectNode?.type !== "marker") {
        this.$message.error("您还未选择学校！");
        return;
      }
      this.areaCircle = new this.aMap.Circle({
        center: this.selectNode.value.data.lnglat,
        radius: this.circleRadius, //半径
        borderWeight: 3,
        strokeColor: "#FF33FF",
        // strokeOpacity: 1,
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillOpacity: 0.4,
        strokeStyle: "dashed",
        strokeDasharray: [10, 10],
        // 线样式还支持 'dashed'
        fillColor: "#1791fc",
        // zIndex: 50,
      });
      this.areaCircle.on("click", (e) => {
        // console.log(e.target.getPath()); // 获取当前范围内包含的坐标点
        const datas = [];
        const allSchools = this.getAllSelectedNodes()
        for (const item of allSchools) {
          this.aMap.GeometryUtil.isPointInRing(item.lnglat, e.target.getPath())
            ? datas.push(item)
            : null;
        }
        // this.infoPop(datas);
        const periodCount = this.getAllPeriodCount(datas)
        this.infoWindow.setContent(
          `<div style="display:flex; align-items: center;flex-direction: column;">
            <div class="relative" style="box-shadow:0px 0px 6px 0px #3fb5f8;background-color: #fff; padding: 10px 20px;text-align: left;border-radius: 8px;max-width: 400px;border: 1px solid #11a4f8">
              <span style="color: #11a4f8">${this.selectNode.value.data.simpleName}<span class="ml-1 mr-1" style="color: #f88e11">${this.circleRadius / 1000}公里</span>内有，学校: ${datas.length}所</span>
              <span class="mr-2">，其中：幼儿园：${periodCount[0]}，小学：${periodCount[1]}，初中：${periodCount[2]}，高中：${periodCount[3]}，特教：${periodCount[4]}</span>
              <span class="cursor-pointer" style="color: #11a4f8;white-space: nowrap;">查看详情></span>
              <div class="absolute" style="background-color: #fff;width: 12px;height: 12px;transform: rotate(135deg);border-color: transparent transparent #3399ff #3399ff;border-width:1px;border-style: solid;top: -6px;left:calc(50% - 6px);"></div>
            </div>
          </div>`
        );
        this.infoWindow.open(this.map, e.lnglat);
        this.infoWindowState = 1
        this.areaCircle.data = datas
        this.selectNode = {
          type: 'area',
          value: this.selectNode.value
        }
      });
      this.map.add(this.areaCircle);
      // 缩放地图到合适的视野级别
      this.map.setFitView([this.areaCircle]);
    },
    getAllPeriodCount(datas) {
      let primarySchoolCount = 0
      let kindergartenCount = 0
      let highSchoolCount = 0
      let juniorHighSchoolCount = 0
      let specialSchoolCount = 0
      for (const item of datas) {
        if (item.learningPeriod === "小学") {
          primarySchoolCount++
        } else if (item.learningPeriod === "幼儿园") {
          kindergartenCount++
        } else if (item.learningPeriod === "高中") {
          highSchoolCount++
        } else if (item.learningPeriod === "初中") {
          juniorHighSchoolCount++
        } else if (item.learningPeriod === "特教") {
          specialSchoolCount++
        }
      }
      return [kindergartenCount, primarySchoolCount, juniorHighSchoolCount, highSchoolCount, specialSchoolCount]
    },
    rulerClick() {
      this.$message({
        message:
          "开启距离量测模式。鼠标在地图上单击绘制量测节点，并计算显示两两节点之间的距离，鼠标左键双击或右键单击结束当前量测操作。",
        type: "success",
      });
      this.mouseTool.rule({
        startMarkerOptions: {
          //可缺省
          icon: new this.aMap.Icon({
            size: new this.aMap.Size(19, 31), //图标大小
            imageSize: new this.aMap.Size(19, 31),
            image: "//webapi.amap.com/theme/v1.3/markers/b/start.png",
          }),
          offset: new this.aMap.Pixel(-9, -31),
        },
        endMarkerOptions: {
          //可缺省
          icon: new this.aMap.Icon({
            size: new this.aMap.Size(19, 31), //图标大小
            imageSize: new this.aMap.Size(19, 31),
            image: "//webapi.amap.com/theme/v1.3/markers/b/end.png",
          }),
          offset: new this.aMap.Pixel(-9, -31),
        },
        lineOptions: {
          //可缺省
          strokeStyle: "solid",
          strokeColor: "#FF33FF",
          strokeOpacity: 1,
          strokeWeight: 2,
        },
        //同 RangingTool 的 自定义 设置，缺省为默认样式
      });
      this.mouseToolState = 'ruler';
    },
    clearMap() {
      this.$confirm(
        "此操作将清楚地图上绘制的所有图形，确定要取消绘制吗?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.map.remove(this.addPolygonList);
          this.mouseToolState = null;
          this.addPolygonList = [];
          this.mouseTool.close(true);
          if (this.areaCircle) {
            this.map.remove(this.areaCircle);
          }
          if (this.customPolygonItem) {
            this.deleteCustomPolygon()
          }
        })
        .catch(() => { });
    },
    initCluster(showNodes, color) {
      const gridSize = 50;
      const count = showNodes.length;
      const _renderClusterMarker = (context) => {
        const div = document.createElement("div");
        const bgColor = color;
        const fontColor = "#fff";
        const borderColor = color;
        const shadowColor = color;
        div.style.backgroundColor = bgColor;
        const size = Math.round(
          30 + Math.pow(context.count / count, 1 / 5) * 20
        );
        div.style.width = div.style.height = size + "px";
        div.style.border = "solid 1px " + borderColor;
        div.style.borderRadius = size / 2 + "px";
        div.style.boxShadow = "0 0 3px " + shadowColor;
        if (this.subjectTypeSelect.length > 0) {
          let total = 0;
          context.clusterData.forEach((element) => {
            if (element.spcount) {
              this.subjectTypeSelect.forEach((fres) => {
                total += Number(element.spcount[fres]);
              });
            }
          });
          div.innerHTML = total;
        } else {
          div.innerHTML = context.count;
        }
        div.style.lineHeight = size + "px";
        div.style.color = fontColor;
        div.style.fontSize = "14px";
        div.style.textAlign = "center";
        context.marker.setOffset(new this.aMap.Pixel(-size / 2, -size / 2));
        context.marker.setContent(div);
        context.marker.data = context;
        context.marker.on("click", this.renderClusterMarkerClick);
      };
      const _renderMarker = (context) => {
        let offset = null;
        let total = 0;
        if (this.subjectTypeSelect.length > 0) {
          this.subjectTypeSelect.forEach((fres) => {
            if (context.data[0].spcount && context.data[0].spcount[fres]) {
              total += Number(context.data[0].spcount[fres]);
            }
          });
        }
        // 选中效果
        if (
          this.selectNode?.type === 'marker' &&
          this.selectNode.value.data.serialId === context.data[0].serialId
          //  && this.infoWindowState === 1
        ) {
          if (this.subjectTypeSelect.length > 0) {
            // context.marker.setContent(
            //   `<div style="width: 200px; height: 60px; display: flex;position: relative">
            //           <img src=${
            //             this.selectedSchoolTypeIcon[this.schoolTypeSelect]
            //           } style="position: absolute;z-index: 3;top:0;left:0;" alt=""/>
            //            <div style="position: absolute;width: 33px;height: 36px;border-radius: 20px;background-color: #ccebc5;z-index: 2;top: 0;left: 5px;""></div>
            //           <div style="margin-left: 5px;height: 36px;background-color: ${color};font-size:14px;display:flex; align-items:center;justify-content: center;color: #fff;border-radius: 18px;padding: 0 10px 0 40px;">` +
            //     "所选学科教师 " +
            //     total ||
            //     "0" +
            //       `</div></div>
            //           </div>`
            // );
            context.marker
              .setContent(`<div style="width: 52px; height: 60px; display: flex;">
                      <img src=${this.selectedSchoolTypeIcon[context.data[0].learningPeriod]
                } alt="">
                      </div>`);
          } else {
            // 没有学科选中
            context.marker
              .setContent(`<div style="width: 52px; height: 60px; display: flex;">
                      <img src=${this.selectedSchoolTypeIcon[context.data[0].learningPeriod]
                } alt="">
                      </div>`);
          }
          offset = new this.aMap.Pixel(-27, -60);
        } else {
          // 未选中效果
          // 如果有学科选中
          if (this.subjectTypeSelect.length > 0) {
            context.marker.setContent(
              `<div style="width: 200px; height: 41px; display: flex;position: relative">
                      <img src=${this.schoolTypeIcon[context.data[0].learningPeriod]
              } style="position: absolute;z-index: 3;top:0;left:0;"/>
                      <div style="position: absolute;width: 31px;height: 36px;border-radius: 10px 17px 17px 10px;background-color: #ccebc5;z-index: 2;top: 0;left: 5px;""></div>
                      <div style="margin-left: 5px;height: 36px;background-color: ${this.tipColor[context.data[0].learningPeriod]};font-size:14px;display:flex; align-items:center;justify-content: center;color: #fff;border-radius: 18px;padding: 0 10px 0 40px;">` +
              "所选学科教师 " +
              total ||
              "0" +
              `</div>
                      </div>`
            );
          } else {
            // 没有学科选中
            context.marker
              .setContent(`<div style="width: 34px; height: 41px; display: flex;">
                      <img src=${this.schoolTypeIcon[context.data[0].learningPeriod]
                } alt="">
                      </div>`);
          }
          offset = new this.aMap.Pixel(-17, -41);
        }
        context.marker.setOffset(offset);
        context.marker.setTop(top);
        context.marker.data = context.data[0];
        context.marker.on("click", this.markerClick);
      };
      this.cluster = new this.aMap.MarkerCluster(this.map, showNodes, {
        gridSize: gridSize, // 设置网格像素大小
        renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
        renderMarker: _renderMarker, // 自定义非聚合点样式
        maxZoom: 15, // 最大聚合zoom
      });
    },
    // 获取数据
    getPositionDatas() {
      this.checkedNames = [];
      this.schoolTypeSelect = ['kindergarten', 'primarySchool', 'juniorHighSchool', 'highSchool', 'specialSchool'];
    },
    renderClusterMarkerClick(e) {
      // this.infoPop(e.target.data.clusterData);
      let zoom = 0;
      if (e.target.data.count > 50) {
        zoom = this.map.getZoom() + 1;
      } else {
        zoom = this.map.getZoom() + 2;
      }
      this.map.setZoomAndCenter(zoom, e.lnglat);
    },
    /* 数据展示弹窗打开前--数据处理 */
    infoPop(clusterData) {
      this.gridData.columnLabel = [];
      this.gridData.columnData = [];

      // 处理表头 start
      this.gridData.columnLabel = [
        {
          property: "sort",
          label: "序号",
          fixed: true,
          with: "50",
        },
        {
          property: "learningPeriod",
          label: "学段",
          fixed: true,
          with: "65",
        },
        {
          property: "ssjz",
          label: "所属街镇",
          fixed: true,
          with: this.subjectTypeSelect.length > 0 ? "auto" : "90",
        },
        {
          property: "unitCode",
          label: "单位编码",
          fixed: true,
          with: this.subjectTypeSelect.length > 0 ? "auto" : "65",
        },
        {
          property: "simpleName",
          label: "学校简称",
          fixed: true,
          with: this.subjectTypeSelect.length > 0 ? "auto" : "120",
        },
        {
          property: "campus",
          label: "校区",
          fixed: true,
          with: this.subjectTypeSelect.length > 0 ? "auto" : "90",
        },
        {
          property: "serialId",
          label: "唯一id",
          notShow: true
        },
      ];

      if (this.subjectTypeSelect.length > 0) {
        this.dialogWidth = "80%";
        let findSubjectType = {};
        this.subjectTypeSelect.forEach((fres) => {
          findSubjectType = this.subjectType.find((fit) => fit.type === fres);
          this.gridData.columnLabel.push({
            label: findSubjectType ? findSubjectType.name : "",
            childFileld: [
              {
                property: "cscount:" + fres,
                dataType: "cscount",
                type: fres,
                label: "测算数据",
                with: "auto",
              },
              {
                property: "xqcount:" + fres,
                dataType: "xqcount",
                type: fres,
                label: "校方需求",
                with: "auto",
              },
              {
                property: "spcount:" + fres,
                dataType: "spcount",
                type: fres,
                label: "师资配备",
                with: "auto",
              },
              {
                property: "cqcount:" + fres,
                dataType: "cqcount",
                type: fres,
                label: "超缺人数",
                with: "auto",
              }
            ],
          });
        });
      } else {
        this.dialogWidth = "95%";
        this.subjectType.forEach((sfres) => {
          this.gridData.columnLabel.push({
            label: sfres.name,
            childFileld: [
              {
                property: "cscount:" + sfres.type,
                dataType: "cscount",
                type: sfres.type,
                label: "测算数据",
                with: "auto",
              },
              {
                property: "xqcount:" + sfres.type,
                dataType: "xqcount",
                type: sfres.type,
                label: "校方需求",
                with: "auto",
              },
              {
                property: "spcount:" + sfres.type,
                dataType: "spcount",
                type: sfres.type,
                label: "师资配备",
                with: "auto",
              },
              {
                property: "cqcount:" + sfres.type,
                dataType: "cqcount",
                type: sfres.type,
                label: "超缺人数",
                with: "auto",
              }
            ],
          });
        });
      }
      // 处理表头 end
      // 处理表身数据 start
      let dataObj = {};
      // let teachers = {};
      // let outFiled = ["sort", "learningPeriod", "unitName", "campus"];
      clusterData.forEach((fres, findex) => {
        dataObj = {};
        this.gridData.columnLabel.forEach((lfres) => {
          dataObj.sort = findex + 1;
          if (lfres.childFileld) {
            lfres.childFileld.forEach((cfres) => {
              // console.log(cfres)
              // console.log(fres)
              if (fres[cfres.dataType] && fres[cfres.dataType][cfres.type]) {
                dataObj[cfres.property] = fres[cfres.dataType][cfres.type];
              }
              // if (!outFiled.includes(cfres.property)) {
              // if (teachers[cfres.property]) {
              // teachers[cfres.property].count += Number(
              // fres[cfres.property]
              // );
              // } else {
              // teachers[cfres.property] = {
              // name: lfres.label + cfres.label,
              // count: Number(fres[cfres.property]),
              // };
              // }
              // }
            });
          } else {
            dataObj[lfres.property] = fres[lfres.property];
          }
        });
        this.gridData.columnData.push(dataObj);
      });
      //let teachersCout = 0;
      //let teachersType = "";
      //for (let key in teachers) {
      //if (teachers[key].count) {
      //if (teachersType) {
      //teachersType =
      //teachersType + `,${teachers[key].name}: ${teachers[key].count}`;
      //} else {
      //teachersType = `${teachers[key].name}: ${teachers[key].count}`;
      //}
      //}
      //if (!key.includes("_CQ")) {
      //teachersCout += teachers[key].count;
      //}
      //}
      //if (teachersCout > 0) {
      //this.gridHeadTip = `${this.gridHeadTip}, 教师: ${teachersCout}人${teachersType ? ", 其中:" + teachersType : ""
      // }`;
      //}
      // 处理表身数据 end
      this.dialogTableVisible = true;
    },
    addPolygon(data, AMap) {
      const polygon = new AMap.Polygon({
        path: data.lnglat,
        fillColor: "#ccebc5",
        strokeOpacity: 1,
        fillOpacity: 0.5,
        strokeColor: "#2b8cbe",
        strokeWeight: 1,
        strokeStyle: "dashed",
        strokeDasharray: [5, 5],
      });
      polygon.on("mouseover", (e) => {
        if (!this.infoWindowState) {
          this.polygonClick(e, "hover");
        }
        polygon.setOptions({
          fillOpacity: 0.7,
          fillColor: "#7bccc4",
        });
      });
      polygon.on("mouseout", () => {
        // console.log(this.infoWindowState);
        if (!this.infoWindowState) {
          this.infoWindow.close();
        }
        polygon.setOptions({
          fillOpacity: 0.5,
          fillColor: "#ccebc5",
        });
      });
      polygon.data = data;
      polygon.on("click", (e) => {
        // console.log(this.mouseToolState);
        if (!this.mouseToolState) {
          this.polygonClick(e, "click");
        } else {
          // console.log(e);
          switch (this.mouseToolState) {
            case "circle": {
              const circle = new this.aMap.Circle({
                center: e.lnglat,
                radius: this.map.getZoom() * -1700 + 25000, //半径
                borderWeight: 3,
                strokeColor: "#FF33FF",
                strokeWeight: 6,
                strokeOpacity: 0.2,
                fillOpacity: 0.4,
                strokeStyle: "dashed",
                strokeDasharray: [10, 10],
                fillColor: "#1791fc",
              });
              const circleEditor = new this.aMap.CircleEditor(this.map, circle);
              circle.on("click", (e) => {
                const datas = this.getAreaDatas(e.target.getPath());
                const periodCount = this.getAllPeriodCount(datas)
                this.infoWindow.setContent(
                  `<div style="display:flex; align-items: center;flex-direction: column;">
                    <div class="relative" style="box-shadow:0px 0px 6px 0px #3fb5f8;background-color: #fff; padding: 10px 20px;text-align: left;border-radius: 8px;max-width: 400px;border: 1px solid #11a4f8">
                      <span style="color: #11a4f8">画区内有，学校: ${datas.length}所</span>
                      <span class="mr-2">，其中：幼儿园：${periodCount[0]}，小学：${periodCount[1]}，初中：${periodCount[2]}，高中：${periodCount[3]}，特教：${periodCount[4]}</span>
                      <span class="cursor-pointer" style="color: #11a4f8;white-space: nowrap;">查看详情></span>
                      <div class="absolute" style="background-color: #fff;width: 12px;height: 12px;transform: rotate(135deg);border-color: transparent transparent #3399ff #3399ff;border-width:1px;border-style: solid;top: -6px;left:calc(50% - 6px);"></div>
                    </div>
                  </div>`
                );
                this.infoWindow.open(this.map, e.lnglat);
                this.infoWindowState = 1
                this.selectNode = {
                  type: 'custom',
                  value: datas
                }
              });
              this.map.add(circle);
              this.deleteCustomPolygon()
              this.customPolygonItem = {
                item: circle,
                editor: circleEditor,
              }
              circleEditor.open();
              break;
            }
            case "rectangle": {
              const southWest = e.lnglat;
              const northEast = new this.aMap.LngLat(
                e.lnglat.lng + this.map.getZoom() * (-0.084) + 1,
                e.lnglat.lat + this.map.getZoom() * (-0.084) + 1
              );

              const bounds = new this.aMap.Bounds(southWest, northEast);
              const rectangle = new this.aMap.Rectangle({
                bounds: bounds,
                strokeColor: "red",
                strokeWeight: 6,
                strokeOpacity: 0.5,
                strokeDasharray: [30, 10],
                strokeStyle: "dashed",
                fillColor: "blue",
                fillOpacity: 0.5,
                cursor: "pointer",
              });
              const rectangleEditor = new this.aMap.RectangleEditor(
                this.map,
                rectangle
              );
              rectangle.on("click", (e) => {
                const datas = this.getAreaDatas(e.target.getPath());
                const periodCount = this.getAllPeriodCount(datas)
                this.infoWindow.setContent(
                  `<div style="display:flex; align-items: center;flex-direction: column;">
                    <div class="relative" style="box-shadow:0px 0px 6px 0px #3fb5f8;background-color: #fff; padding: 10px 20px;text-align: left;border-radius: 8px;max-width: 400px;border: 1px solid #11a4f8">
                      <span style="color: #11a4f8">画区内有，学校: ${datas.length}所</span>
                      <span class="mr-2">，其中：幼儿园：${periodCount[0]}，小学：${periodCount[1]}，初中：${periodCount[2]}，高中：${periodCount[3]}，特教：${periodCount[4]}</span>
                      <span class="cursor-pointer" style="color: #11a4f8;white-space: nowrap;">查看详情></span>
                      <div class="absolute" style="background-color: #fff;width: 12px;height: 12px;transform: rotate(135deg);border-color: transparent transparent #3399ff #3399ff;border-width:1px;border-style: solid;top: -6px;left:calc(50% - 6px);"></div>
                    </div>
                  </div>`
                );
                this.infoWindow.open(this.map, e.lnglat);
                this.infoWindowState = 1
                this.selectNode = {
                  type: 'custom',
                  value: datas
                }
              });
              rectangle.on("dblclick", () => {
                rectangleEditor.close();
              });
              this.map.add(rectangle);
              this.deleteCustomPolygon()
              this.customPolygonItem = {
                item: rectangle,
                editor: rectangleEditor,
              }
              rectangleEditor.open();
              break;
            }
          }
        }
      });
      this.map.add(polygon);
    },
    getAreaDatas(pathList) {
      const datas = [];
      if (pathList.length > 0) {
        const allSchools = this.getAllSelectedNodes()
        for (const item of allSchools) {
          if (item.lnglat) {
            this.aMap.GeometryUtil.isPointInRing(item.lnglat, pathList)
              ? datas.push(item)
              : null;
          }
        }
      }
      return datas;
    },
    clickPolygon() {
      this.selectNode = null;
      this.map.setFitView();
    },
    delPolygon() {
      if (this.cluster) {
        this.cluster.setMap(null);
        this.cluster = null;
      }
    },
    mapZoomChange(index) {
      this.map.setZoom(
        index === "1" ? this.map.getZoom() + 1 : this.map.getZoom() - 1
      );
      this.$message({
        message: "当前地图放大倍率为" + this.map.getZoom(),
        type: "success",
      });
    },
    polygonClick(e, type = "") {
      if (type === "click") {
        if (this.selectNode?.type === "polygon") {
          this.selectNode.value.setOptions({
            fillOpacity: 0.5,
            fillColor: "#ccebc5",
          });
        }
        e.target.setOptions({
          fillOpacity: 0.7,
          fillColor: "#7bccc4",
        });
        this.selectNode = {
          type: 'polygon',
          value: e.target
        }
        this.infoWindowState = 1
        this.infoWindow.setContent(
          `<div style="display:flex; align-items: center;flex-direction: column;">
            <div class="relative" style="box-shadow:0px 0px 6px 0px #3fb5f8;background-color: #fff; padding: 10px 20px;text-align: left;border-radius: 8px;max-width: 400px;border: 1px solid #11a4f8">
              <span class="mr-2">${e.target.data.name}</span>
              <span class="cursor-pointer" style="color: #11a4f8;white-space: nowrap;">查看详情></span>
              <div class="absolute" style="background-color: #fff;width: 12px;height: 12px;transform: rotate(135deg);border-color: transparent transparent #3399ff #3399ff;border-width:1px;border-style: solid;top: -6px;left:calc(50% - 6px);"></div>
            </div>
          </div>`
        );
      } else {
        this.infoWindow.setContent(
          `<div style="display:flex; align-items: center;flex-direction: column;">
            <div class="relative" style="box-shadow:0px 0px 6px 0px #3fb5f8;background-color: #fff; padding: 10px 20px;text-align: left;border-radius: 8px;max-width: 400px;border: 1px solid #11a4f8">
              <span class="mr-2">${e.target.data.name}</span>
              <div class="absolute" style="background-color: #fff;width: 12px;height: 12px;transform: rotate(135deg);border-color: transparent transparent #3399ff #3399ff;border-width:1px;border-style: solid;top: -6px;left:calc(50% - 6px);"></div>
            </div>
          </div>`
        );
      }
      this.infoWindow.open(this.map, e.lnglat);
    },
    searchSchools() {
      if (!this.searchKey) {
        this.$message.error("请输入搜索条件！");
        return;
      }
      if (!this.schoolTypeSelect.length === 0) {
        this.$message.error("请先选择学段！");
        return;
      }
      const schoolsList = [];
      const allSchools = this.getAllSelectedNodes()
      allSchools.forEach((item) => {
        if (item.unitName.includes(this.searchKey)) {
          schoolsList.push(item);
        }
      });
      this.delPolygon();
      if (schoolsList.length === 0) {
        this.$message.error("当前学段内未搜索有关该关键字的学校！");
        return;
      }
      if (this.schoolTypeSelect.length === 1) {
        switch (this.schoolTypeSelect[0]) {
          case "kindergarten":
            this.showPolygon(schoolsList, this.color[0]);
            break;
          case "primarySchool":
            this.showPolygon(schoolsList, this.color[1]);
            break;
          case "juniorHighSchool":
            this.showPolygon(schoolsList, this.color[2]);
            break;
          case "highSchool":
            this.showPolygon(schoolsList, this.color[3]);
            break;
          case "specialSchool":
            this.showPolygon(schoolsList, this.color[4]);
            break;
          default:
            break;
        }
      } else if (this.schoolTypeSelect.length > 0) {
        this.showPolygon(schoolsList, this.color[5]);
      }
      this.map.setFitView();
      this.clearAreaCircle();
    },
    /* 点击单位事件处理 */
    markerClick(e) {
      this.map.setCenter(e.target.data.lnglat);
      if (!(e.target.data.serialId === this.selectNode?.value?.data?.serialId)) {
        this.selectNode = {
          type: "marker",
          value: e.target
        }
      }

      this.infoWindow.setContent(
        `<div style="display:flex; align-items: center;flex-direction: column;">
          <div class="relative" style="box-shadow:0px 0px 6px 0px #3fb5f8;background-color: #fff; padding: 10px 20px;text-align: left;border-radius: 8px;max-width: 400px;border: 1px solid #11a4f8">
            <span class="mr-2">${e.target.data.simpleName}  ${e.target.data.campus}</span>
            <span class="cursor-pointer" style="color: #11a4f8;white-space: nowrap;">查看详情></span>
            <div class="absolute" style="background-color: #fff;width: 12px;height: 12px;transform: rotate(135deg);border-color: transparent transparent #3399ff #3399ff;border-width:1px;border-style: solid;top: -6px;left:calc(50% - 6px);"></div>
          </div>
        </div>`
      );
      this.infoWindow.open(this.map, e.target.getPosition());
      this.infoWindowState = 1;

    },
    markerTip() {
      if (this.selectNode?.type === 'marker') {
        this.gridHeadTip = "";
        this.gridHeadTitle = "";
        this.gridHeadTitle = `${this.selectNode.value.data.unitName}师资统计`;
        this.gridHeadTip = `${this.selectNode.value.data.unitName}`;
        this.infoPop([this.selectNode.value.data]);
      } else if (this.selectNode?.type === 'polygon') {
        if (this.schoolTypeSelect.length === 0) {
          this.$message.error("您还未选择学段！");
          return;
        }

        const allSchools = this.getAllSelectedNodes()
        let schoolsInPolygon = []
        for (const school of allSchools) {
          if (
            school.ssjzcode === this.selectNode.value.data.serialId
          ) {
            schoolsInPolygon.push(school);
          }
        }
        schoolsInPolygon = Array.from(new Set(schoolsInPolygon));

        this.gridHeadTitle = `${this.selectNode.value.data.name}区域内学校及师资统计（${schoolsInPolygon.length}所）`;
        this.gridHeadTip = `${this.selectNode.value.data.name}区域内有: 学校: ${schoolsInPolygon.length}所`;
        this.infoPop(schoolsInPolygon);
      } else if (this.selectNode.type === 'area') {
        this.gridHeadTitle = ``;
        this.gridHeadTip = ``;
        let range = `${this.circleRadius / 1000}公里`;
        this.gridHeadTitle = `${this.selectNode.value.data.unitName}${range}内学校及师资统计（${this.areaCircle.data.length}所）`;
        this.gridHeadTip = `${this.selectNode.value.data.unitName}${range}内有: 学校: ${this.areaCircle.data.length}所`;
        this.infoPop(this.areaCircle.data);
      } else if (this.selectNode.type === 'custom') {
        this.gridHeadTitle = ``;
        this.gridHeadTip = ``;
        this.gridHeadTitle = `绘图内学校及师资统计（${this.selectNode.value.length}所）`;
        this.gridHeadTip = `绘图内有: 学校: ${this.selectNode.value.length}所`;
        this.infoPop(this.selectNode.value);
      }
    },
    rightMenuClass() {
      if (this.showSchoolType && !this.showSubjectType) {
        return "right-menu-onlySchool";
      } else if (!this.showSchoolType && !this.showSubjectType) {
        return "right-menu-allFalse";
      }
    },
    /* 弹窗关闭 */
    dialogClose() {
      this.dialogTableVisible = !this.dialogTableVisible;
      this.dialogFullscreen = false;
    },
    /* 弹窗中 统计提示 点击展开折叠 */
    tipEllipsisClick() {
      this.tipEllipsis = !this.tipEllipsis;
      if (!this.tipEllipsis) {
        this.gridHeadTipHeight = "32";
      } else {
        const detailDom = this.$refs.countTip;
        this.gridHeadTipHeight = detailDom.scrollHeight;
      }
    },
    /* 表格合计处理 */
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value)) && column.level > 1) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          // sums[index] += ' 人';
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },
  },
};
</script>

<style scoped>
#map-area {
  width: 100%;
  height: 100%;
}

.left-top-tools {
  top: 70px;
  right: calc(2% + 168px);
}

.right-menu {
  height: 83%;
  right: 2%;
  top: 7%;
}

.right-menu-onlySchool {
  top: calc(90% - 298px);
  height: 298px;
}

.right-menu-allFalse {
  top: calc(90% - 84px);
  height: 84px;
}

.map-area-main {
  width: 100%;
  height: 100vh;
  z-index: 22;
}

/* maptools要和rightmenu右对齐 改rightMenu的时候记得改一下maptools的 */
.map-tools {
  right: 3%;
  top: 8%;
}

.menu-all-area {
  padding-bottom: 6px;
  border: solid 1px #3399ff;
  border-radius: 6px;
  background-color: #fff;
  box-shadow: 2px 2px 7px 0px rgba(8, 115, 224, 0.35);
}

.menu-area {
  width: 145px;
  height: 100%;
  overflow: auto;
}

.menu-area::-webkit-scrollbar {
  width: 8px;
  height: 10px;
}

.menu-area::-webkit-scrollbar-track {
  border-radius: 2px;
}

.menu-area::-webkit-scrollbar-thumb {
  background: #bdc6cb;
  border-radius: 10px;
  border: 2px solid transparent;
  background-clip: padding-box;
}

.menu-area::-webkit-scrollbar-thumb:hover {
  background: #333;
}

.menu-area::-webkit-scrollbar-corner {
  background: #179a16;
}

.menu-outline {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 12px;
  height: 42px;
  background-color: #e6f3ff;
}

.menu-outline-first {
  border-radius: 6px 6px 0 0;
}

.check-button {
  width: 90%;
  border-radius: 8px;
  height: 40px;
  margin: 10px 0;
  background-color: #dcdfe4;
}

.button-style {
  padding: 10px 25px;
  border-radius: 20px;
  border: 1px solid #dcdfe4;
  background-color: #fff;
  margin: 0 10px;
}

.child-button {
  margin: 13px 16px 0;
  height: 28px;
  border-radius: 14px;
  font-size: 16px;
  border: solid 1px #3399ff;
  color: #0994ec;
  background-color: #fff;
}

.active-button {
  color: #fff;
  background-color: #129ef7;
}

.active-school-type {
  border: 0;
  color: #fff;
}

.child-button:last-child {
  margin-bottom: 8px;
}

.ability-point {
  margin: 0 13px;
}

.duihaoIcon {
  width: 16px;
  height: 15px;
}

.tip-area {
  height: 60px;
  padding: 4px 13px 0px;
  bottom: calc(10% - 60px);
  right: calc(2% + 246px);
  background-color: #ffffff;
  box-shadow: 2px 2px 7px 0px rgba(8, 115, 224, 0.35);
  border: solid 1px #3399ff;
  border-radius: 6px;
  display: flex;
  align-items: center;
}

.eye-area {
  bottom: calc(10% - 62px);
  right: 1.5%;
  width: 49px;
  height: 49px
}

.ability-point-img {
  width: 24px;
  height: 24px;
  margin-bottom: 4px;
  display: inline-block;
}

.ability-point-name {
  font-size: 16px;
  letter-spacing: 1px;
  color: #606060;
}

.search-area {

  width: 280px;
  height: 40px;
  background-color: #ffffff;
  box-shadow: 2px 2px 7px 0px rgba(13, 142, 241, 0.35);
  border-radius: 8px;
  border: solid 1px #1cabf9;
}

.search-area>>>.el-input__inner {
  border: 0;
}

.search-area>>>.el-input--small .el-input__inner {
  height: 36px;
  line-height: 36px;
}

.search-area-icon {
  width: 14%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pop-area>>>.el-table .el-table__cell {
  padding: 4px 0;
}

.map-head {
  height: 54px;
  width: 100vw;
  position: absolute;
  /* top: -6px; */
  z-index: 1;
  background-image: url("../assets/images/headBackground.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

.map-head-name {
  width: 100vw;
  line-height: 54px;
  z-index: 1;
  font-size: 26px;
  letter-spacing: 2px;
  color: #ffffff;
  text-shadow: 3px 3px 5px #0058be;
}

::v-deep .el-dialog__header {
  display: none;
}

::v-deep .el-dialog__body {
  padding: 0px;
}

.count-head {
  height: 36px;
  line-height: 36px;
  color: #ffffff;
  font-size: 18px;
  position: relative;
  background-color: #0d8def;
}

.count-head .el-icon-close {
  position: absolute;
  right: 15px;
  top: 8px;
  font-size: 21px;
}

.count-head .count-head-export {
  position: absolute;
  right: 80px;
  top: 2px;
  font-size: 16px;
}

.count-head .count-head-change {
  position: absolute;
  left: 5px;
  top: 0px;
  font-size: 14px;
}

.dialog-full-screen {
  position: absolute;
  right: 45px;
  top: 8px;
  font-size: 21px;
}

.pop-area {
  height: calc(100% - 36px);
  padding: 6px 8px 8px;
}

.count-info {
  height: 32px;
  line-height: 24px;
  text-align: left;
  background-color: #ddf5f1;
  display: flex;
  margin-bottom: 6px;
  padding: 3px 0 3px 10px;
}

.count-info-img {
  width: 22px;
  height: 22px;
  border-radius: 4px;
  background: #11c8b5;
  margin-right: 4px;
}

.count-info-img img {
  display: inline-block;
  font-size: 10px;
  width: 12px;
  height: 15px;
}

.count-info-tip {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
}

.count-info-btn {
  color: #3278ff;
  margin-right: 6px;
}

/* ::v-deep .el-table {
  overflow: auto;
}

::v-deep .el-table .el-table__body-wrapper,
::v-deep .el-table .el-table__header-wrapper,
::v-deep .el-table .el-table__footer-wrapper {
  overflow: visible;
}

::v-deep .el-table::after {
  position: relative !important;
} */
::v-deep .el-table .el-table__footer-wrapper .cell {
  font-weight: bold;
}

::v-deep .el-table .el-table__body-wrapper {
  z-index: 1;
}



.triangle {
  height: 12px;
  width: 12px;
  border-color: #3399ff #3399ff transparent transparent;
  border-width: 1px;
  border-style: solid;
  background-color: white;
}

.triangle-right {
  transform: rotate(45deg);
  position: absolute;
  right: -6px;
}

.triangle-bottom {
  transform: rotate(135deg);
  position: absolute;
  bottom: -6px;
  left: 74px;
}

.condition-tool {
  color: #ffffff;
  font-size: 16px;
}

.condition-tool-left {
  height: 42px;
  left: 18px;
  top: 6px;
  display: flex;
  align-items: center;
}

.condition-tool-left img {
  width: 19px;
  height: 14px;
}

.condition-tool-right {
  height: 42px;
  top: 6px;
  right: 14px;
  display: flex;
  align-items: center;
}

.condition-tool-right span {
  margin-right: 4px;
}

.condition-tool-right img {
  width: 17px;
  height: 10px;
}

* {
  -webkit-tap-highlight-color: transparent;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
</style>
